package com.dragon.mapper;

import com.dragon.pojo.Problem.ProblemList;
import com.dragon.pojo.Training.Training;
import com.dragon.pojo.Training.TrainingInfo;
import com.dragon.pojo.Training.TrainingList;
import com.dragon.pojo.Training.TrainingSelectInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface TrainingMapper {
    Integer getSelectTotal(TrainingSelectInfo info);

    List<TrainingList> getTrainingList(TrainingSelectInfo info);

    @Select("SELECT t.id, training_name, description, problem_total, count(t.id=tp.training_id and tp.problem_id=r.problem_id and CASE WHEN r.complete_status = 2 THEN 1 END) as accepted_total," +
            " creator, create_time, update_time from training t left join training_problem tp on t.id = tp.training_id left join\n" +
            "(SELECT problem_id,MAX(complete_status) as complete_status from record where user_id=#{userId} group by problem_id,user_id) r on tp.problem_id = r.problem_id where training_id=#{trainingId} group by t.id, t.training_name, t.problem_total")
    Training getTrainingInfo(Integer trainingId, Integer userId);

    @Select("select p.id,title_name,algorithm_tag,difficulty, IFNULL(max(r.complete_status), 0) as complete_status " +
            "from problem p join training_problem tp on p.id = tp.problem_id and tp.training_id=#{trainingId} " +
            "left join record r on p.id = r.problem_id AND r.user_id=#{userId} " +
            "GROUP BY p.id, title_name, algorithm_tag, difficulty, tp.`order` order by tp.`order`")
    List<ProblemList> getTrainingProblemList(Integer trainingId, Integer userId);

    void addTraining(TrainingInfo info);

    void addTrainingProblem(List<Integer> problemIdList, Integer trainingId);

    @Delete("DELETE from training where id=#{trainingId}")
    void deleteTraining(Integer trainingId);

    @Delete("DELETE from training_problem where training_id=#{trainingId}")
    void deleteTrainingProblem(Integer trainingId);

    @Update("UPDATE training set training_name=#{trainingName},description=#{description},problem_total=#{problemTotal},update_time=now() where id=#{trainingId}")
    void updateTraining(TrainingInfo info);
}
